-- author: Allez
-- some rewrited

local module = {}
module.name = "ActionBars"
module.Init = function()
	if not SCDB.modules[module.name] then return end
	local settings = SCDB
	
	
	
	-- Config start
	local size = ActionButton1:GetWidth()
	local spacing = size/8
	local expspace = UnitLevel("player") < MAX_PLAYER_LEVEL_TABLE[3] and 6 or 0
	
	local frame_positions = {
		[1]	=	{ a = "BOTTOM",     x = 0,   y = spacing/2  },				-- MainBar
		[2]	=	{ a = "BOTTOM",     x = 0,   y = (size+spacing*3)+expspace},	-- MultiBarBottomLeft
		[3]	=	{ a = "BOTTOM",     x = 0,   y = (size+spacing*3)*2  },		-- MultiBarBottomRight
		[4]	=	{ a = "RIGHT",      x = -(size+spacing), y = -100 },						-- MultiBarLeft
		[5]	=	{ a = "RIGHT",      x = -3,  y = -100 },						-- MultiBarRight
		[6]	=	{ a = "BOTTOM",     x = 0,   y = 120 },						-- PetBar
		[7]	=	{ a = "BOTTOMLEFT", x = 12,  y = 210 },						-- ShapeShiftBar
		[8]	=	{ a = "BOTTOM",     x = 280, y = 80  },						-- VehicleBar
	}
	-- Config end
	
	local CreateBarFrame = function(name, pos)
		local bar = CreateFrame("Frame", name, UIParent, "SecureHandlerStateTemplate")
		bar:SetFrameStrata("BACKGROUND")
		bar:SetPoint(pos.a, pos.x, pos.y)
		return bar
	end
	
	local function PaintTextures()
		local r1, g1, b1, a1 = 1,1,1,1 -- top color
		local r2, g2, b2, a2 = .4, .4, .4, 1 -- bottom color

		for i,v in pairs({
			-- Action bars
			MainMenuMaxLevelBar0,
			MainMenuMaxLevelBar1,
			MainMenuBarTexture0,
			MainMenuBarTexture1,
			MainMenuBarTexture2,
			MainMenuBarTexture3,
			MainMenuXPBarTextureRightCap,
			MainMenuXPBarTextureMid,
			MainMenuXPBarTextureLeftCap,
			ActionBarUpButton:GetRegions(),
			ActionBarDownButton:GetRegions(),
			BonusActionBarFrame:GetRegions(),
			KeyRingButton:GetRegions(),	
			select(2, BonusActionBarFrame:GetRegions()),
			
			-- Unit frames
			PlayerFrameTexture,
			TargetFrameTextureFrameTexture,
			FocusFrameTextureFrameTexture,
			TargetFrameToTTextureFrameTexture,
			FocusFrameToTTextureFrameTexture,
			PetFrameTexture,
			
			-- Minimap
			MinimapBackdrop,
			MinimapBorder,
			MiniMapMailBorder,
			MiniMapTrackingButtonBorder,
			MinimapBorderTop,
			MinimapZoneTextButton,
			MiniMapWorldMapButton,
			MiniMapWorldMapButton,
			MiniMapWorldIcon,
			MinimapZoomIn:GetRegions(),
			MinimapZoomOut:GetRegions(),
			TimeManagerClockButton:GetRegions(),
			MiniMapWorldMapButton:GetRegions(),
			select(6, GameTimeFrame:GetRegions()),
			
			-- Exp bubble dividers
			MainMenuXPBarDiv1,
			MainMenuXPBarDiv2,
			MainMenuXPBarDiv3,
			MainMenuXPBarDiv4,
			MainMenuXPBarDiv5,
			MainMenuXPBarDiv6,
			MainMenuXPBarDiv7,
			MainMenuXPBarDiv8,
			MainMenuXPBarDiv9,
			MainMenuXPBarDiv10,
			MainMenuXPBarDiv11,
			MainMenuXPBarDiv12,
			MainMenuXPBarDiv13,
			MainMenuXPBarDiv14,
			MainMenuXPBarDiv15,
			MainMenuXPBarDiv16,
			MainMenuXPBarDiv17,
			MainMenuXPBarDiv18,
			MainMenuXPBarDiv19,
			
			-- Chat frame buttons
			select(2, FriendsMicroButton:GetRegions()),
			ChatFrameMenuButton:GetRegions(),
			ChatFrame1ButtonFrameUpButton:GetRegions(),
			ChatFrame1ButtonFrameDownButton:GetRegions(),
			select(2, ChatFrame1ButtonFrameBottomButton:GetRegions()),
			ChatFrame2ButtonFrameUpButton:GetRegions(),
			ChatFrame2ButtonFrameDownButton:GetRegions(),
			select(2, ChatFrame2ButtonFrameBottomButton:GetRegions()),
			
			-- Chat edit box
			select(6, ChatFrame1EditBox:GetRegions()),
			select(7, ChatFrame1EditBox:GetRegions()),
			select(8, ChatFrame1EditBox:GetRegions()),
			select(5, ChatFrame1EditBox:GetRegions()),
			
			-- Micro menu buttons
			select(2, SpellbookMicroButton:GetRegions()),
			select(3, CharacterMicroButton:GetRegions()),
			select(2, TalentMicroButton:GetRegions()),
			select(2, AchievementMicroButton:GetRegions()),
			select(2, QuestLogMicroButton:GetRegions()),
			select(2, GuildMicroButton:GetRegions()),
			select(3, PVPMicroButton:GetRegions()),
			select(2, LFDMicroButton:GetRegions()),
			select(4, MainMenuMicroButton:GetRegions()),
			select(2, HelpMicroButton:GetRegions()),
			
			-- Other
			select(2, CastingBarFrame:GetRegions()),
			select(2, MirrorTimer1:GetRegions()),
			MainMenuBarLeftEndCap,
			MainMenuBarRightEndCap,
		}) do
			if v:GetObjectType() == "Texture" then
				v:SetVertexColor(1, 1, 1)
				v:SetDesaturated(1)
				v:SetVertexColor(r2, g2, b2)
			end
		end
		
		-- Desaturation fix for elite target texture (thanks SDPhantom!)
		hooksecurefunc("TargetFrame_CheckClassification", function(self)
			self.borderTexture:SetDesaturated(1)
		end)
		
		-- Game tooltip
		TOOLTIP_DEFAULT_COLOR = { r = r1 * .6, g = g1 * .6, b = b1 * .6 }
		TOOLTIP_DEFAULT_BACKGROUND_COLOR = { r = r2 * .1, g = g2 * .1, b = b2 * .1}
		
		MinimapBackdrop:SetBackdropBorderColor(.4,.4,.4)
	end
	
	

	local SetButtons = function(bar, button, num, orient, bsize)
		local size = bsize or size
		spacing = size/8
		for i = 1, num do
			_G[button..i]:ClearAllPoints()
			_G[button..i]:SetAttribute("unit2", "player")
			_G[button..i]:SetWidth(size)
			_G[button..i]:SetHeight(size)
			_G[button..i].SetSize = function() end
			_G[button..i].SetWidth = function() end
			_G[button..i].SetHeight = function() end
			
			if _G[button..i.."Shine"] then
				_G[button..i.."Shine"]:SetWidth(size)
				_G[button..i.."Shine"]:SetHeight(size)
				_G[button..i.."Shine"].SetWidth = function() end
				_G[button..i.."Shine"].SetHeight = function() end
			end
			if _G[button..i.."AutoCastable"] then
				_G[button..i.."AutoCastable"]:SetWidth(size*2)
				_G[button..i.."AutoCastable"]:SetHeight(size*2)
				_G[button..i.."AutoCastable"].SetWidth = function() end
				_G[button..i.."AutoCastable"].SetHeight = function() end
			end
			
			if _G[button..i.."Cooldown"] then
				_G[button..i.."Cooldown"]:ClearAllPoints()
				_G[button..i.."Cooldown"]:SetPoint("CENTER")
				_G[button..i.."Cooldown"]:SetWidth(size-6)
				_G[button..i.."Cooldown"]:SetHeight(size-6)
				_G[button..i.."Cooldown"].SetWidth = function() end
				_G[button..i.."Cooldown"].SetHeight = function() end
			end

			if i == 1 then
				_G[button..i]:SetPoint("TOPLEFT", bar, "TOPLEFT", 0, 0)
			else
				if orient == "H" then
					_G[button..i]:SetPoint("TOPLEFT", _G[button..(i-1)], "TOPRIGHT", spacing, 0)
				else
					_G[button..i]:SetPoint("TOPLEFT", _G[button..(i-1)], "BOTTOMLEFT", 0, -spacing)
				end
			end
		end
		if orient == "H" then
			bar:SetWidth(size*num + spacing*(num-1))
			bar:SetHeight(size)
		else
			bar:SetWidth(size)
			bar:SetHeight(size*num + spacing*(num-1))
		end
	end

	local bar1 = CreateBarFrame("mod_MainBar", frame_positions[1])
	local bar2 = CreateBarFrame("mod_MultiBarBottomLeftBar", frame_positions[2])
	local bar3 = CreateBarFrame("mod_MultiBarBottomRightBar", frame_positions[3])
	local bar4 = CreateBarFrame("mod_MultiBarLeftBar", frame_positions[4])
	local bar5 = CreateBarFrame("mod_MultiBarRightBar", frame_positions[5])
	local bar6 = CreateBarFrame("mod_PetBar", frame_positions[6])
	local bar7 = CreateBarFrame("mod_ShapeShiftBar", frame_positions[7])
	local bar8 = CreateBarFrame("mod_VehicleBar", frame_positions[8])
	
	 
	local VehicleLeaveButton = CreateFrame("Button", "VehicleLeaveButton1", UIParent)
	VehicleLeaveButton:SetNormalTexture("Interface\\Vehicles\\UI-Vehicles-Button-Exit-Up")
	VehicleLeaveButton:SetPushedTexture("Interface\\Vehicles\\UI-Vehicles-Button-Exit-Down")
	VehicleLeaveButton:SetHighlightTexture("Interface\\Vehicles\\UI-Vehicles-Button-Exit-Down")
	VehicleLeaveButton:RegisterEvent("UNIT_ENTERED_VEHICLE")
	VehicleLeaveButton:RegisterEvent("UNIT_EXITED_VEHICLE")
	
	VehicleLeaveButton:SetScript("OnClick", function(self)
		VehicleExit()
	end)
	VehicleLeaveButton:SetScript("OnEvent", function(self)
		if CanExitVehicle() then
			self:Show()
		else
			self:Hide()
		end
	end)
	VehicleLeaveButton:Hide()

	for _, v in pairs({
		MultiBarBottomLeft,
		MultiBarBottomRight,
		MultiBarLeft,
		MultiBarRight,
		PetActionBarFrame,
		ShapeshiftBarFrame,
	}) do
		v:UnregisterAllEvents()
		v:SetParent(UIParent)
		v:SetWidth(0.01)
	end
	
	for _, obj in pairs({
		SlidingActionBarTexture0,
		SlidingActionBarTexture1,
		BonusActionBarFrameTexture0,
		BonusActionBarFrameTexture1,
		BonusActionBarFrame,
		ShapeshiftBarLeft,
		ShapeshiftBarRight,
		ShapeshiftBarMiddle,
		MainMenuBar,
		VehicleMenuBar,
		PossessBarFrame,
	}) do
		if obj:GetObjectType() == 'Texture' then
			obj:SetTexture("")
		else
			obj:SetScale(0.001)
			obj:SetAlpha(0)
		end
	end
	
	SetButtons(bar1, "ActionButton", NUM_ACTIONBAR_BUTTONS, "H")
	SetButtons(bar2, "MultiBarBottomLeftButton", NUM_MULTIBAR_BUTTONS, "H")
	SetButtons(bar3, "MultiBarBottomRightButton", NUM_MULTIBAR_BUTTONS, "H")
	SetButtons(bar4, "MultiBarLeftButton", NUM_MULTIBAR_BUTTONS, "V")
	SetButtons(bar5, "MultiBarRightButton", NUM_MULTIBAR_BUTTONS, "V")
	SetButtons(bar6, "PetActionButton", NUM_PET_ACTION_SLOTS, "H", 22)
	SetButtons(bar7, "ShapeshiftButton", NUM_SHAPESHIFT_SLOTS, "H", 30)
	SetButtons(bar8, "VehicleLeaveButton", 1, "H", 40)

	MainMenuBarLeftEndCap:SetTexture("Interface\\PlayerActionBarAlt\\SpellBar-Stone_left")
	MainMenuBarRightEndCap:SetTexture("Interface\\PlayerActionBarAlt\\SpellBar-Stone_left")
	MainMenuBarLeftEndCap:SetVertexColor(1,1,1)
	MainMenuBarRightEndCap:SetVertexColor(1,1,1)
	MainMenuBarLeftEndCap:SetParent(bar1)
	MainMenuBarLeftEndCap:ClearAllPoints()
	MainMenuBarLeftEndCap:SetPoint("BOTTOMRIGHT", bar1, "BOTTOMLEFT", 23, -5)
	MainMenuBarLeftEndCap:SetWidth(132)
	MainMenuBarLeftEndCap:SetHeight(132/2)
	MainMenuBarRightEndCap:SetParent(bar1)
	MainMenuBarRightEndCap:ClearAllPoints()
	MainMenuBarRightEndCap:SetPoint("BOTTOMLEFT", bar1, "BOTTOMRIGHT", -23, -5) 
	MainMenuBarRightEndCap:SetWidth(132)
	MainMenuBarRightEndCap:SetHeight(132/2)
	MainMenuBarLeftEndCap:SetDrawLayer("BACKGROUND")
	MainMenuBarRightEndCap:SetDrawLayer("BACKGROUND")
	
	MainMenuBarTexture0:SetParent(bar1)
	MainMenuBarTexture0:SetDrawLayer("BORDER")
	MainMenuBarTexture0:ClearAllPoints()
	MainMenuBarTexture0:SetPoint("TOPLEFT", bar1, "TOPLEFT", -spacing, spacing/2)
	MainMenuBarTexture0:SetPoint("BOTTOMRIGHT", bar1, "BOTTOM", 0, -spacing/2)
	
	MainMenuBarTexture1:SetParent(bar1)
	MainMenuBarTexture1:SetDrawLayer("BORDER")
	MainMenuBarTexture1:ClearAllPoints()
	MainMenuBarTexture1:SetPoint("TOPLEFT", bar1, "TOP", 0, spacing/2)
	MainMenuBarTexture1:SetPoint("BOTTOMRIGHT", bar1, "BOTTOMRIGHT", spacing, -spacing/2)
	
	if expspace == 0 then
		MainMenuMaxLevelBar0:SetParent(bar1)
		MainMenuMaxLevelBar0:SetDrawLayer("BACKGROUND")
		MainMenuMaxLevelBar0:ClearAllPoints()
		MainMenuMaxLevelBar0:SetPoint("TOPLEFT", bar1, "TOPLEFT", -spacing, spacing*2)
		MainMenuMaxLevelBar0:SetPoint("BOTTOMRIGHT", bar1, "TOP", 0, 0)

		MainMenuMaxLevelBar1:SetParent(bar1)
		MainMenuMaxLevelBar1:SetDrawLayer("BACKGROUND")
		MainMenuMaxLevelBar1:ClearAllPoints()
		MainMenuMaxLevelBar1:SetPoint("TOPLEFT", bar1, "TOP", 0, spacing*2)
		MainMenuMaxLevelBar1:SetPoint("BOTTOMRIGHT", bar1, "TOPRIGHT", 5, 0)
	end

	if expspace > 0 then
		local expbar = CreateFrame("StatusBar", "expbar", bar1)
		local exo = expbar:CreateTexture("exo", "BORDER"); exo:SetAllPoints(expbar); exo:SetTexture(0,0,0,1)
		local exc = expbar:CreateTexture("exc", "BORDER"); exc:SetPoint("TOPLEFT", 0, 0); exc:SetSize(0,10); exc:SetTexture(1,1,1,1); exc:SetBlendMode("ADD")
		local ext = CreateFrame("Button", "ext", expbar); ext:SetSize(32,32); ext:SetPoint("CENTER"); ext:SetNormalTexture("Interface\\MainMenuBar\\UI-ExhaustionTickNormal"); ext:SetHighlightTexture("Interface\\MainMenuBar\\UI-ExhaustionTickHighlight"); ext:GetHighlightTexture():SetBlendMode("ADD"); ext:SetScript("OnLeave", GameTooltip_Hide); ext:SetScript("OnEnter", ExhaustionToolTipText)
		expbar.lockShow = 0
		local efs = expbar:CreateFontString("efs", "OVERLAY", "GameFontHighlightSmall")
		efs:SetPoint("CENTER")
		SetTextStatusBarText(expbar, efs)
		
		expbar:SetScript("OnEnter", function(self, ...)
			TextStatusBar_UpdateTextString(self)
			ShowTextStatusBarText(self)
			GameTooltip_AddNewbieTip(self, XPBAR_LABEL, 1.0, 1.0, 1.0, NEWBIE_TOOLTIP_XPBAR, 1)
			GameTooltip:Show()
		end)
		expbar:SetScript("OnLeave", function(self, ...)
			HideTextStatusBarText(self)
			GameTooltip:Hide()
			expbar.lockShow = 0
		end)

		local cc = CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[select(2, UnitClass("player"))] or RAID_CLASS_COLORS[select(2, UnitClass("player"))] or { r=.5, g=.5, b=.5 } 
		expbar:SetStatusBarTexture("Interface\\TargetingFrame\\UI-StatusBar")
		expbar:SetSize(bar1:GetWidth(), 10)
		expbar:SetPoint("BOTTOM", bar1, "TOP", 0, 4)
		expbar:RegisterEvent("PLAYER_ENTERING_WORLD")
		expbar:RegisterEvent("PLAYER_XP_UPDATE")
		expbar:RegisterEvent("UPDATE_EXHAUSTION")
		expbar:RegisterEvent("PLAYER_LEVEL_UP")
		expbar:RegisterEvent("PLAYER_UPDATE_RESTING")
		expbar:SetScript("OnEvent", function(self, ...)
			local currXP, nextXP = UnitXP("player"), UnitXPMax("player")
			self:SetMinMaxValues(math.min(0, currXP), nextXP)
			self:SetValue(currXP)
			local treshold = GetXPExhaustion()
			local eID, eName, eMult = GetRestState()
			if (eID >= 3) then
				ext:SetPoint("CENTER", expbar, "RIGHT", 0, 0)
			end		
			
			if (not treshold) then
				ext:Hide()
				exc:Hide()
			else
				local tick = math.max(((currXP + treshold) / nextXP) * expbar:GetWidth(), 0)
				ext:ClearAllPoints()
				
				if (tick > expbar:GetWidth()) then
					ext:Hide()
				else
					ext:Show()
					ext:SetPoint("CENTER", expbar, "LEFT", tick, 0)
					exc:Show()
					exc:SetPoint("TOPRIGHT", expbar, "TOPLEFT", tick, 0)
				end
			end		

			local eID = GetRestState()
			if (eID == 1) then
				expbar:SetStatusBarColor(0.0, 0.39, 0.88, 1.0)
				exc:SetVertexColor(0.0, 0.39, 0.88, 0.15)
				ext:GetHighlightTexture():SetVertexColor(0.0, 0.39, 0.88)
			elseif (eID == 2) then
				expbar:SetStatusBarColor(0.58, 0.0, 0.55, 1.0)
				exc:SetVertexColor(0.58, 0.0, 0.55, 0.15)
				ext:GetHighlightTexture():SetVertexColor(0.58, 0.0, 0.55)
			end
			
			local divWidth = bar1:GetWidth()/20
			local xpos = divWidth - 4.5
			for i=1,19 do
				local texture = _G["expbardiv"..i]
				if not texture then
					texture = self:CreateTexture("expbardiv"..i, "OVERLAY")
					texture:SetTexture("Interface\\MainMenuBar\\UI-XP-Bar")
					texture:SetSize(8,8)
					if SCDB["Main"].ClassColored == true then
						texture:SetVertexColor(cc.r*.5, cc.g*.5, cc.b*.5)
					else
						texture:SetVertexColor(.4,.4,.4)
					end				
					texture:SetTexCoord( 0.01562500, 0.15625000, 0.01562500, 0.17187500)
				end
				local xalign = floor(xpos)
				texture:SetPoint("LEFT", xalign, 1)
				xpos = xpos + divWidth
			end
			
			if not expbar:IsShown() then
				ext:Hide()
			end
		end)
		
		MainMenuXPBarTextureLeftCap:SetParent(expbar)
		MainMenuXPBarTextureLeftCap:ClearAllPoints()
		MainMenuXPBarTextureLeftCap:SetPoint("LEFT", expbar, "LEFT", -3, 0)
		MainMenuXPBarTextureLeftCap:SetDrawLayer("OVERLAY")
		
		MainMenuXPBarTextureRightCap:SetParent(expbar)
		MainMenuXPBarTextureRightCap:ClearAllPoints()
		MainMenuXPBarTextureRightCap:SetPoint("RIGHT", expbar, "RIGHT", 3, 0)
		MainMenuXPBarTextureRightCap:SetDrawLayer("OVERLAY")
		
		MainMenuXPBarTextureMid:SetParent(expbar)
		MainMenuXPBarTextureMid:ClearAllPoints()
		MainMenuXPBarTextureMid:SetPoint("LEFT", MainMenuXPBarTextureLeftCap, "RIGHT", 0, 0)
		MainMenuXPBarTextureMid:SetPoint("RIGHT", MainMenuXPBarTextureRightCap, "LEFT", 0, 0)
		MainMenuXPBarTextureMid:SetDrawLayer("OVERLAY")		
	end
	
	local function UpdateActionBarsPos()
		anchor = bar1
		local anchorOffset = 4 + expspace

		if MultiBarBottomLeft:IsShown() then
			anchor = bar2
			anchorOffset = 4
		else
			anchor = bar1
			anchorOffset = 4 + expspace*2
		end

		if MultiBarBottomRight:IsShown() then
			bar3:ClearAllPoints()
			bar3:SetPoint("BOTTOMLEFT", anchor, "TOPLEFT", 0, anchorOffset )
			anchor = bar3
			anchorOffset = 4
		end
		
		if ShapeshiftButton1:IsShown() then
			bar7:ClearAllPoints()
			bar7:SetPoint("BOTTOMLEFT", anchor, "TOPLEFT", 0, anchorOffset)
			anchorOffset = 4
		end	
		
		
		if MultiCastActionBarFrame:IsShown() then
			UIPARENT_MANAGED_FRAME_POSITIONS['MultiCastActionBarFrame'] = {baseY = 0, bottomLeft = anchorOffset, reputation = 0, maxLevel = 0, anchorTo = anchor:GetName(), point = "BOTTOMLEFT", rpoint = "TOPLEFT", xOffset = 0}
			MultiCastActionBarFrame:SetScript("OnUpdate", nil)
			MultiCastActionBarFrame_OnUpdate = function() end
			MultiCastActionBarFrame:SetScript("OnShow", nil)
			MultiCastActionBarFrame:SetScript("OnHide", nil)
			MultiCastActionBarFrame:SetParent(bar1)
			MultiCastActionBarFrame:ClearAllPoints()
			MultiCastActionBarFrame:SetPoint("BOTTOMLEFT", anchor, "TOPLEFT", 0, anchorOffset)
			MultiCastFlyoutFrame:SetFrameStrata("HIGH")
			
			MultiCastActionBarFrame.SetParent = function() end
			--MultiCastActionBarFrame.SetPoint = function() end
			MultiCastRecallSpellButton.SetPoint = function() end
			anchorOffset = 4
		end

		bar6:ClearAllPoints()
		bar6:SetPoint("BOTTOMRIGHT", anchor, "TOPRIGHT", 0, anchorOffset)
		anchor = bar6
		anchorOffset = 4
	end

	InterfaceOptionsActionBarsPanelBottomLeft:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelBottomRight:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelAlwaysShowActionBars:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelLockActionBars:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelSecureAbilityToggle:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelRightTwo:HookScript("OnClick", UpdateActionBarsPos)
	InterfaceOptionsActionBarsPanelRight:HookScript("OnClick", UpdateActionBarsPos)
	----------------------------------------------------------------------------------------
	--	Setup Main Action Bar by Tukz
	----------------------------------------------------------------------------------------

	--[[ 
		Bonus bar classes id

		DRUID: Caster: 0, Cat: 1, Tree of Life: 2, Bear: 3, Moonkin: 4
		WARRIOR: Battle Stance: 1, Defensive Stance: 2, Berserker Stance: 3 
		ROGUE: Normal: 0, Stealthed: 1
		PRIEST: Normal: 0, Shadowform: 1
		
		When Possessing a Target: 5
	]]--

	local Page = {
		["DRUID"] = "[bonusbar:1,nostealth] 7; [bonusbar:1,stealth] 8; [bonusbar:2] 8; [bonusbar:3] 9; [bonusbar:4] 10;",		
		["WARRIOR"] = "[bonusbar:1] 7; [bonusbar:2] 8; [bonusbar:3] 9;",
		["PRIEST"] = "[bonusbar:1] 7;",
		["ROGUE"] = "[bonusbar:1] 7; [bonusbar:2] 7;",
		["WARLOCK"] = "[form:2] 10;",
		["DEFAULT"] = "[bar:2] 2; [bar:3] 3; [bar:4] 4; [bar:5] 5; [bar:6] 6; [bonusbar:5] 11;",
	}

	local GetBar = function()
		local condition = Page["DEFAULT"]
		local class = select(2, UnitClass('player'))
		local page = Page[class]
		if page then
			condition = condition.." "..page
		end
		condition = condition.." 1"
		return condition
	end
	
	bar1:RegisterEvent("PLAYER_LOGIN")
	bar1:RegisterEvent("PLAYER_ENTERING_WORLD")
	bar1:RegisterEvent("PLAYER_TALENT_UPDATE")
	bar1:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED")
	bar1:RegisterEvent("KNOWN_CURRENCY_TYPES_UPDATE")
	bar1:RegisterEvent("CURRENCY_DISPLAY_UPDATE")
	bar1:RegisterEvent("BAG_UPDATE")

	bar1:SetScript("OnEvent", function(self, event, ...)
		if event == "PLAYER_LOGIN" then
			PetActionBarFrame.showgrid = 1
			
			local button
			for i = 1, NUM_ACTIONBAR_BUTTONS do
				button = _G["ActionButton"..i]
				self:SetFrameRef("ActionButton"..i, button)
			end	
			self:Execute([[
				buttons = table.new()
				for i = 1, 12 do
					table.insert(buttons, self:GetFrameRef("ActionButton"..i))
				end
			]])
			self:SetAttribute("_onstate-page", [[ 
				for i, button in ipairs(buttons) do
					button:SetAttribute("actionpage", tonumber(newstate))
				end
			]])
			RegisterStateDriver(self, "page", GetBar())
		elseif event == "PLAYER_ENTERING_WORLD" then
			MainMenuBar_UpdateKeyRing()
			for i = 1, NUM_ACTIONBAR_BUTTONS do
				_G["ActionButton"..i]:SetParent(UIParent)
			end
		elseif event == "PLAYER_TALENT_UPDATE" or event == "ACTIVE_TALENT_GROUP_CHANGED" then
			if not InCombatLockdown() then
				RegisterStateDriver(self, "page", GetBar())
			end
		else
			if not InCombatLockdown() then
				UpdateActionBarsPos()
			end
			MainMenuBar_OnEvent(self, event, ...)
		end
	end)
	
	bar6:RegisterEvent("PLAYER_LOGIN")
	bar6:RegisterEvent("PLAYER_CONTROL_LOST")
	bar6:RegisterEvent("PLAYER_CONTROL_GAINED")
	bar6:RegisterEvent("PLAYER_ENTERING_WORLD")
	bar6:RegisterEvent("PLAYER_FARSIGHT_FOCUS_CHANGED")
	bar6:RegisterEvent("PET_BAR_UPDATE")
	bar6:RegisterEvent("PET_BAR_UPDATE_USABLE")
	bar6:RegisterEvent("PET_BAR_UPDATE_COOLDOWN")
	bar6:RegisterEvent("PET_BAR_HIDE")
	bar6:RegisterEvent("UNIT_PET")
	bar6:RegisterEvent("UNIT_FLAGS")
	bar6:RegisterEvent("UNIT_AURA")
	
	bar6:SetScript("OnEvent", function(self, event, ...)
		if event == "PLAYER_LOGIN" then
			PetActionBarFrame.showgrid = 1 -- hack to never hide pet button. :X
			
			local button
			for i = 1, 10 do
				button = _G["PetActionButton"..i]
				button:SetParent(self)
				self:SetAttribute("addchild", button)
			end
			RegisterStateDriver(self, "visibility", "[pet,novehicleui,nobonusbar:5] show; hide")
		else
			PetActionBar_Update()
			UpdateActionBarsPos()
		end
	end)
	
	local States = {
		["DRUID"] = "show",
		["WARRIOR"] = "show",
		["PALADIN"] = "show",
		["DEATHKNIGHT"] = "show",
		["ROGUE"] = "show,",
		["PRIEST"] = "show,",
		["HUNTER"] = "show,",
		["WARLOCK"] = "show,",
	}

	bar7:RegisterEvent("PLAYER_LOGIN")
	bar7:RegisterEvent("PLAYER_ENTERING_WORLD")
	bar7:RegisterEvent("UPDATE_SHAPESHIFT_FORMS")
	bar7:RegisterEvent("UPDATE_SHAPESHIFT_USABLE")
	bar7:RegisterEvent("UPDATE_SHAPESHIFT_COOLDOWN")
	bar7:RegisterEvent("UPDATE_SHAPESHIFT_FORM")
	bar7:RegisterEvent("ACTIONBAR_PAGE_CHANGED")
	bar7:SetScript("OnEvent", function(self, event, ...)
		if event == "PLAYER_LOGIN" then
			PaintTextures()
			local button
			for i = 1, NUM_SHAPESHIFT_SLOTS do
				button = _G["ShapeshiftButton"..i]
				button:ClearAllPoints()
				button:SetParent(self)
				button:SetFrameStrata("LOW")
				if i == 1 then
					button:SetPoint("LEFT")
				else
					local previous = _G["ShapeshiftButton"..i-1]
					button:SetPoint("LEFT", previous, "RIGHT", spacing, 0)
				end
				button.SetPoint = function() end
				local _, name = GetShapeshiftFormInfo(i)
				if name then
					button:Show()
				end
			end
			RegisterStateDriver(self, "visibility", States[select(2, UnitClass("player"))] or "hide")
		elseif event == "UPDATE_SHAPESHIFT_FORMS" then
			-- Update Shapeshift Bar Button Visibility
			-- I seriously don't know if it's the best way to do it on spec changes or when we learn a new stance.
			if InCombatLockdown() then return end -- > just to be safe ;p
			local button
			for i = 1, NUM_SHAPESHIFT_SLOTS do
				button = _G["ShapeshiftButton"..i]
				local _, name = GetShapeshiftFormInfo(i)
				if name then
					button:Show()
				else
					button:Hide()
				end
			end
			--ShapeshiftBar_Update()
		elseif event == "PLAYER_ENTERING_WORLD" then
			ShapeshiftBar_Update()
		else
			ShapeshiftBar_Update()
		end
	end)	
end
tinsert(SuperClassic.modules, module) -- finish him!